<template>
    <div class="flex_row w100 h100" style="justify-content: space-between;">
        <div class="flex_col_start h100" style="overflow-y: scroll;">
            <DeviceItem v-for="(item, index) in ctx.devices" :key="index" @delete="onClickDelete(item)"
                @detail="onClickDetail(item)" :device="item" />
        </div>
        <CreateDeviceParts :name="name" :id="id" @created="onCreated" />
        <div></div>
    </div>
</template>

<script lang="ts" setup>
import CreateDeviceParts from '@/components/CreateDeviceParts.vue';
import DeviceItem from '@/components/DeviceItem.vue';
import router from '@/router';
import { deleteDevice, queryDevice, type TbDevice } from '@/service/device';
import { runAction } from '@/utils/ui';
import { reactive } from 'vue';
import { useRoute } from 'vue-router';


const route = useRoute();

const id = parseInt(route.query.id as string);
const name = route.query.name as string;

interface Ctx {
    devices: TbDevice[]
}

const ctx = reactive<Ctx>({
    devices: []
});

async function onCreated() {
    await runAction('更新', '', async () => {
        await init();
    })
}

async function onClickDetail(item: TbDevice) {
    router.push({
        path: '/device_detail',
        query: {
            'id': item.id,
        }
    })
}

async function onClickDelete(item: TbDevice) {
    await runAction('删除', '', async () => {
        await deleteDevice(item.id);
        await init();
    });
}

async function init() {
    const items = await queryDevice(id);
    ctx.devices = items;
}

init();

</script>
